﻿
namespace Huirui.Cavan.Presentation.Seedwork
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using System.Threading;
    using System.Web.Mvc;
    using Huirui.Cavan.Core.Extension;
    using Huirui.Cavan.Application.MainBoundedContext.SystemModule;
    using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = true)]
    public class UserDescriptionAttribute : ActionFilterAttribute
    {
        #region OnResult
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            this.Log().Info("OnResultExecuting--started-UserDescriptionFilter");
            SetCurrentUserModel(filterContext);
            base.OnActionExecuting(filterContext);
            this.Log().Info("OnResultExecuting-finished-UserDescriptionFilter");
        }
        #endregion OnResult

        #region CurrentUserModel
        protected virtual void SetCurrentUserModel(ControllerContext filterContext)
        {
            var controller = filterContext.Controller as IWebController<IWebModel>;
            if (controller.Is())
            {
                var model = controller.Model.MasterModel.CurrentUserModel;

                SetUserInitials(model);
                if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
                {
                    model.CurrentStateDescription = "logon";
                    model.CurrentStateEntity = "logon";
                }
                else
                {
                    model.CurrentStateDescription = "Role";
                    model.CurrentStateEntity = SecurityAppService.UserAccount.Role.Name;
                }

                if (Thread.CurrentPrincipal.Identity.IsAuthenticated
                    && Thread.CurrentPrincipal.Identity.AuthenticationType.Equals("Forms"))
                {
                    model.LogoutUrl = controller.Url.Action("logout", "UserAccount");
                }
            }
        }

        protected static void SetUserInitials(ICurrentUserModel model)
        {
            if (null != model)
            {
                model.UserAccountID = SecurityAppService.UserAccount.Id;
                model.UserLogin = SecurityAppService.UserAccount.Name;
                model.UserName = SecurityAppService.UserAccount.Name;
                model.UserRole = (SystemIdentifier.Role)SecurityAppService.UserRole.Id;
                model.RoleUseDenied = SecurityAppService.UserRole.IsUseDenied;
                model.CorporationCode = SecurityAppService.Corporation.Id;
            }
        }
        #endregion CurrentUserModel
    }
}